package com.micromall.admin;

import com.alibaba.fastjson.JSON;
import com.micromall.repository.AdminUserMapper;
import com.micromall.repository.entity.AdminUser;
import com.micromall.utils.ArgumentValidException;
import com.micromall.utils.CommonEnvConstants;
import com.micromall.utils.CookieUtils;
import com.micromall.web.resp.ResponseEntity;
import com.micromall.web.security.annotation.Authentication;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * <pre>
 * 后台管理登录
 *
 * @author Zhang Zhongxiang<zhangzxiang91@gmail.com>
 * @ClassName: AuthorizationController
 * @date 2014年12月21日 上午5:38:33
 */
@RestController
@RequestMapping(value = "/admin")
@Authentication(force = false)
public class AuthorizationController {

	@Resource
	private AdminUserMapper adminUserMapper;

	@RequestMapping(value = "/login", method = {RequestMethod.POST})
	public ResponseEntity login(HttpServletRequest request, HttpServletResponse response, String username, String password) throws Exception {
		if (StringUtils.isBlank(username)) {
			throw new ArgumentValidException("用户名不能为空");
		}
		if (StringUtils.isBlank(password)) {
			throw new ArgumentValidException("密码不能为空");
		}
		String _password = adminUserMapper.selectPasswordByUsername(username);
		password = DigestUtils.md5Hex("$" + password + "$");
		if (!password.equals(_password)) {
			throw new ArgumentValidException("用户名或密码错误");
		}

		AdminUser adminUser = adminUserMapper.getByUsername(username);
		String sid = UUID.randomUUID().toString().replace("-", "");
		CookieUtils.addCookie(response, CommonEnvConstants.ADMIN_LOGIN_SESSION_COOKIE_SID, sid);
		CookieUtils.addCookie(response, CommonEnvConstants.ADMIN_LOGIN_SESSION_COOKIE_USER, URLEncoder.encode(JSON.toJSONString(adminUser)));
		/*cacheService.set(CommonEnvConstants.LOGIN_SESSION_KEY, sid, loginUser, CommonEnvConstants.SESSION_CACHE_EXPRIED);*/
		request.getSession().setAttribute(CommonEnvConstants.ADMIN_LOGIN_SESSION_KEY, username);
		return ResponseEntity.Success();
	}

	@RequestMapping(value = "/logout", method = {RequestMethod.GET})
	public String logout(HttpServletRequest request) {
		request.getSession().invalidate();
		return "redirect:" + CommonEnvConstants.ADMIN_LOGIN_REDIRECT_URL;
	}
}
